﻿using AutoMapper;
using MediatR;
using Medical.Api.Read.Application.Command.RBAC;
using Medical.Api.Read.Dto.RBAC;
using Medical.Domain.RBAC;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.RBAC
{
    /// <summary>
    /// 获取权限树列表
    /// </summary>
    public class GetPermissionTreeListHandler : IRequestHandler<GetPermissionTreeListCommand, ApiResult<List<PermissionTreeDto>>>
    {
        private readonly IBaseRepository<PermissionModel> _permissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPermissionTreeListHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="permissionRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public GetPermissionTreeListHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<GetPermissionTreeListHandler> logger)
        {
            _permissionRepository = permissionRepository;
            this.mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 获取权限树列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<PermissionTreeDto>>> Handle(GetPermissionTreeListCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<PermissionTreeDto>> res = new ApiResult<List<PermissionTreeDto>>();
            res.Data = GetTree(0);
            res.Code = ApiEnums.Success;
            res.Msg = "获取权限树列表成功";
            return Task.FromResult(res);
        }

        private List<PermissionTreeDto> GetTree(int permissionId)
        {
            var tree = _permissionRepository.GetAll().Where(x => x.ParentId == permissionId).ToList();
            var dtos = mapper.Map<List<PermissionTreeDto>>(tree);
            foreach (var item in dtos)
            {
                item.Children = GetTree(item.Id);
            }
            return dtos;
        }
    }
}
